# -* - coding: UTF-8 -* -
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
from driver import ClientDriver
from fastcgi import *
import os
import logging
#队列驱动抽像类
class FastcgiClient(ClientDriver):  
	def create(self):  
		self.fcgi_port = self.config.get_int('fast_cgi','port',9000)
		self.fcgi_host = self.config.get('fast_cgi','host','127.0.0.1')
		self.fcgi_unix_socket = self.config.get('fast_cgi','unix_socket','False')
		self.http_host = self.config.get('fast_cgi','http_host','127.0.0.1')
		self.document_root = self.config.get('fast_cgi','document_root','')
		self.url = self.config.get('fast_cgi','url','/queue.php')

		currnt_path=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
		if not self.document_root:
			self.document_root=currnt_path
		else:
			self.document_root=self.document_root.replace('{$path}',currnt_path)
		
		if self.fcgi_unix_socket.endswith('.pid') or self.fcgi_unix_socket.endswith('.sock'):
			self.client = CGIClient(self.fcgi_unix_socket)			
		else:
			self.client = CGIClient(host=self.fcgi_host,
									port=self.fcgi_port)
	
	#发送请求
	def send(self,body,command=''):
		#logging.info(body)
		content = "_message="+body
		path_info=''
		if command:
			path_info='/'+command.replace('.','/')
		query_string = "s="+path_info
		env = {
		   'SCRIPT_FILENAME': self.document_root+self.url,
		   'QUERY_STRING': query_string,
		   'REQUEST_METHOD': 'POST',
		   'SCRIPT_NAME': self.url,
		   'REQUEST_URI': path_info,
		   'HTTP_HOST':'127.0.0.1',
		   'HTTP_USER_AGENT': 'Coop Transform/1.0',
		   'HTTP_X_REQUESTED_WITH':'xmlhttprequest',
		   'HTTP_CONNECTION': 'keep-alive',
		   'PATH_INFO': path_info,
		   'REDIRECT_STATUS': '200',
		   'CONTENT_TYPE': 'application/x-www-form-urlencoded',#'application/json',
		   'CONTENT_LENGTH': str(len(content)),
		   'DOCUMENT_ROOT': self.document_root,
		   'DOCUMENT_URI': self.url,
		   'REMOTE_ADDR': '127.0.0.1',
		   'REMOTE_PORT': '9982',	
		   'GATEWAY_INTERFACE': 'CGI/1.1',		   
		   'SERVER_SOFTWARE': 'COOP/2.0',		   
		   'SERVER_PROTOCOL' : 'HTTP/1.1',
		   'SERVER_ADDR': self.fcgi_host,
		   'SERVER_PORT': str(self.fcgi_port),
		   'SERVER_NAME': self.fcgi_host}
		try:
			#logging.error(env)
			#logging.error(content)
			ret=self.client(env,content)
		except Exception as e:
			ret = ['','','error']
			logging.error('FastcgiClient error')
			logging.exception(e)
		return ret[2].strip()